<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF生成表单</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        neutral: '#F2F3F5',
                        dark: '#1D2129',
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .transition-custom {
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            }
            .shadow-custom {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            }
            .border-gradient {
                border-image: linear-gradient(to right, #165DFF, #36CFC9) 1;
            }
        }
    </style>
</head>
<body class="font-inter bg-gray-50 min-h-screen">
<div class="container mx-auto px-4 py-8 max-w-4xl">
    <div class="bg-white rounded-xl shadow-custom p-6 md:p-8 mb-6 transform hover:translate-y-[-2px] transition-custom">
        <h1 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-dark mb-6 flex items-center">
            <i class="fa fa-file-pdf-o text-primary mr-3"></i>PDF生成表单
        </h1>

        <form id="pdfForm" class="space-y-6">
            <!-- 表单字段区域 -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div class="space-y-2">
                    <label for="sampleName" class="block text-sm font-medium text-gray-700">
                        <i class="fa fa-tag text-primary mr-1"></i>样本名称
                    </label>
                    <div class="relative">
                            <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                                <i class="fa fa-pencil"></i>
                            </span>
                        <input type="text" id="sampleName" name="sampleName"
                               class="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom outline-none"
                               placeholder="请输入样本名称" required>
                    </div>
                </div>

                <div class="space-y-2">
                    <label for="sampleType" class="block text-sm font-medium text-gray-700">
                        <i class="fa fa-folder-open text-primary mr-1"></i>样本类型
                    </label>
                    <div class="relative">
                            <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                                <i class="fa fa-list-ul"></i>
                            </span>
                        <input type="text" id="sampleType" name="sampleType"
                               class="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom outline-none"
                               placeholder="请选择样本类型" required>
                    </div>
                </div>
            </div>

            <!-- 图片上传区域 -->
            <div class="space-y-4">
                <label class="block text-sm font-medium text-gray-700">
                    <i class="fa fa-image text-primary mr-1"></i>上传图片
                </label>

                <div id="imageUploadContainer" class="relative border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-primary transition-custom">
                    <input type="file" id="imageUpload" accept="image/*" class="absolute inset-0 w-full h-full opacity-0 cursor-pointer" multiple>

                    <div id="uploadPlaceholder" class="space-y-2">
                        <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 text-primary mb-2">
                            <i class="fa fa-cloud-upload text-2xl"></i>
                        </div>
                        <p class="text-gray-500">拖放图片到这里，或<span class="text-primary font-medium">点击上传</span></p>
                        <p class="text-xs text-gray-400">支持 JPG, PNG, GIF 格式，单张不超过5MB</p>
                    </div>

                    <div id="imagePreviewContainer" class="hidden grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3 mt-4">
                        <!-- 图片预览会动态添加到这里 -->
                    </div>
                </div>
            </div>

            <!-- 提交按钮 -->
            <div class="flex flex-col sm:flex-row gap-3 pt-4">
                <button type="button" id="resetButton" class="flex-1 py-3 px-4 bg-gray-100 text-gray-700 rounded-lg font-medium transition-custom hover:bg-gray-200 flex items-center justify-center">
                    <i class="fa fa-refresh mr-2"></i>重置
                </button>
                <button type="submit" id="generateButton" class="flex-1 py-3 px-4 bg-primary text-white rounded-lg font-medium transition-custom hover:bg-primary/90 focus:ring-4 focus:ring-primary/30 flex items-center justify-center group">
                    <i class="fa fa-file-pdf-o mr-2 group-hover:animate-pulse"></i>
                    <span>生成PDF文件</span>
                </button>
            </div>
        </form>
    </div>

    <!-- 结果区域 -->
    <div id="resultContainer" class="hidden bg-white rounded-xl shadow-custom p-6 md:p-8 transform hover:translate-y-[-2px] transition-custom">
        <h2 class="text-xl font-bold text-dark mb-4 flex items-center">
            <i class="fa fa-check-circle text-green-500 mr-2"></i>操作结果
        </h2>

        <div id="resultContent" class="space-y-4">
            <div class="bg-gray-50 p-4 rounded-lg">
                <h3 class="font-medium text-gray-800 mb-2">请求参数</h3>
                <div id="formDataDisplay" class="text-sm text-gray-600 whitespace-pre-wrap"></div>
            </div>

            <div class="bg-gray-50 p-4 rounded-lg">
                <h3 class="font-medium text-gray-800 mb-2">图片信息</h3>
                <div id="imageDataDisplay" class="text-sm text-gray-600 whitespace-pre-wrap"></div>
            </div>

            <div class="flex justify-end mt-6">
                <a id="downloadLink" href="#" target="_blank" class="py-2 px-4 bg-primary text-white rounded-lg font-medium transition-custom hover:bg-primary/90 flex items-center">
                    <i class="fa fa-download mr-2"></i>下载PDF文件
                </a>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 获取DOM元素
        const pdfForm = document.getElementById('pdfForm');
        const imageUpload = document.getElementById('imageUpload');
        const imagePreviewContainer = document.getElementById('imagePreviewContainer');
        const uploadPlaceholder = document.getElementById('uploadPlaceholder');
        const resetButton = document.getElementById('resetButton');
        const generateButton = document.getElementById('generateButton');
        const resultContainer = document.getElementById('resultContainer');
        const formDataDisplay = document.getElementById('formDataDisplay');
        const imageDataDisplay = document.getElementById('imageDataDisplay');
        const downloadLink = document.getElementById('downloadLink');

        // 存储上传的图片信息
        let uploadedImages = [];
        let imageFiles = []; // 存储实际的文件对象

        // 图片上传处理
        imageUpload.addEventListener('change', handleImageUpload);

        // 拖放上传
        const dropArea = document.getElementById('imageUploadContainer');
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, preventDefaults, false);
        });

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        ['dragenter', 'dragover'].forEach(eventName => {
            dropArea.addEventListener(eventName, highlight, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, unhighlight, false);
        });

        function highlight() {
            dropArea.classList.add('border-primary');
            dropArea.classList.add('bg-primary/5');
        }

        function unhighlight() {
            dropArea.classList.remove('border-primary');
            dropArea.classList.remove('bg-primary/5');
        }

        dropArea.addEventListener('drop', handleDrop, false);

        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            handleImageFiles(files);
        }

        function handleImageUpload(e) {
            const files = e.target.files;
            handleImageFiles(files);
        }

        function handleImageFiles(files) {
            if (files.length === 0) return;

            // 清除之前的数据
            uploadedImages = [];
            imageFiles = [];

            // 隐藏上传提示
            uploadPlaceholder.classList.add('hidden');
            imagePreviewContainer.classList.remove('hidden');
            imagePreviewContainer.innerHTML = '';

            // 处理每个文件
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                if (!file.type.match('image.*')) continue;

                const reader = new FileReader();
                reader.onload = function(e) {
                    // 添加到图片预览
                    addImagePreview(file.name, e.target.result);

                    // 存储图片信息和文件对象
                    uploadedImages.push({
                        name: file.name,
                        type: file.type,
                        size: formatFileSize(file.size)
                    });
                    
                    imageFiles.push(file);
                }
                reader.readAsDataURL(file);
            }

            // 重置文件输入
            imageUpload.value = '';
        }

        function addImagePreview(fileName, dataUrl) {
            const imageCard = document.createElement('div');
            imageCard.className = 'relative bg-white rounded-lg overflow-hidden shadow-sm border border-gray-200 transition-custom hover:shadow-md';
            imageCard.innerHTML = `
                    <div class="aspect-square overflow-hidden">
                        <img src="${dataUrl}" alt="${fileName}" class="w-full h-full object-cover transition-transform duration-500 hover:scale-110">
                    </div>
                    <div class="p-2">
                        <p class="text-xs truncate">${fileName}</p>
                    </div>
                    <button type="button" class="absolute top-2 right-2 w-6 h-6 flex items-center justify-center rounded-full bg-red-500/80 text-white opacity-0 group-hover:opacity-100 transition-custom hover:bg-red-600" data-name="${fileName}">
                        <i class="fa fa-times"></i>
                    </button>
                `;

            imagePreviewContainer.appendChild(imageCard);

            // 添加删除功能
            const deleteButton = imageCard.querySelector('button');
            deleteButton.addEventListener('click', function() {
                const name = this.getAttribute('data-name');
                imageCard.remove();

                // 从数组中移除
                const index = uploadedImages.findIndex(img => img.name === name);
                if (index !== -1) {
                    uploadedImages.splice(index, 1);
                    imageFiles.splice(index, 1);
                }

                // 如果没有图片了，显示上传提示
                if (uploadedImages.length === 0) {
                    uploadPlaceholder.classList.remove('hidden');
                    imagePreviewContainer.classList.add('hidden');
                }
            });
        }

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 重置表单
        resetButton.addEventListener('click', function() {
            pdfForm.reset();
            uploadedImages = [];
            imageFiles = [];
            imagePreviewContainer.innerHTML = '';
            uploadPlaceholder.classList.remove('hidden');
            imagePreviewContainer.classList.add('hidden');
            resultContainer.classList.add('hidden');
        });

        // 表单提交处理
        pdfForm.addEventListener('submit', async function(e) {
            e.preventDefault();

            // 获取表单数据
            const formData = new FormData(this);
            const formDataObj = {};
            formData.forEach((value, key) => {
                formDataObj[key] = value;
            });

            // 构建图片数据 (使用固定键名)
            const imageDataObj = {};
            if (imageFiles.length > 0) {
                imageDataObj["testPicture_af_image"] = imageFiles[0]; // 只取第一张图片
            }

            // 显示加载状态
            generateButton.disabled = true;
            generateButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i><span>正在生成...</span>';

            try {
                // 调用API生成PDF
                const response = await generatePdf(formDataObj, imageDataObj);

                // 显示结果
                formDataDisplay.textContent = JSON.stringify(formDataObj, null, 2);
                imageDataDisplay.textContent = JSON.stringify({
                    "testPicture_af_image": imageDataObj["testPicture_af_image"] ?
                        `图片文件: ${imageDataObj["testPicture_af_image"].name}` :
                        "未上传图片"
                }, null, 2);
                
                // 设置下载链接
                downloadLink.href = URL.createObjectURL(response);
                downloadLink.download = "测试.pdf";
                downloadLink.onclick = function(e) {
                    e.stopPropagation();
                };

                resultContainer.classList.remove('hidden');

                // 平滑滚动到结果区域
                resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
            } catch (error) {
                alert('生成PDF失败: ' + error.message);
            } finally {
                // 恢复按钮状态
                generateButton.disabled = false;
                generateButton.innerHTML = '<i class="fa fa-file-pdf-o mr-2"></i><span>生成PDF文件</span>';
            }
        });

        async function generatePdf(formData, imageData) {

            console.log("表单数据:", formData);
            console.log("图片数据:", imageData);
            // 创建用于发送到后端的FormData
            const requestFormData = new FormData();
            
            // 添加表单数据
            const formDataJson = JSON.stringify(formData);
            requestFormData.append("formData", formDataJson);

            // 添加图片数据（二进制）
            if (imageData["testPicture_af_image"]) {
                // const imageDataJson = JSON.stringify(imageData);
                // requestFormData.append("imageData", imageData["testPicture_af_image"]);
                // requestFormData.append("imageData", imageData);
                console.log("111", imageFiles[0])
                requestFormData.append('testPicture_af_image', imageFiles[0])
            }

            // 调用后端API
            const response = await fetch('http://localhost:8888/pdfFill/generate', {
                method: 'POST',
                body: requestFormData
            });

            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
            }

            // 返回PDF的Blob对象
            return await response.blob();
        }

        // 添加动画效果
        const animateOnScroll = () => {
            const elements = document.querySelectorAll('.animate-on-scroll');
            elements.forEach(element => {
                const elementPosition = element.getBoundingClientRect().top;
                const windowHeight = window.innerHeight;
                if (elementPosition < windowHeight - 100) {
                    element.classList.add('fade-in');
                }
            });
        };

        window.addEventListener('scroll', animateOnScroll);
        animateOnScroll(); // 初始检查
    });
</script>
</body>
</html>